package com.juc.atomics;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicMarkableReference;

/**
 * @Author Zan
 * @Create 2024/5/11 14:36
 * @ClassName : AtomicMarkableReferenceDemo
 * @Description : TODO 请用一句话描述该类的功能
 */
public class AtomicMarkableReferenceDemo {

    private static AtomicMarkableReference markableReference = new AtomicMarkableReference(100, false);

    public static void main(String[] args) {
        new Thread(() -> {
            boolean marked = markableReference.isMarked();
            System.out.println(Thread.currentThread().getName() + "\t" + "默认标识：" + marked);

            // 暂停1s，等待后面的t2线程和t1拿到一样的flag标识，都是false
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            markableReference.compareAndSet(100, 1000, marked, !marked);

        }, "t1").start();

        new Thread(() -> {
            boolean marked = markableReference.isMarked();
            System.out.println(Thread.currentThread().getName() + "\t" + "默认标识：" + marked);

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            boolean b = markableReference.compareAndSet(100, 2000, marked, !marked);

            System.out.println(Thread.currentThread().getName() + "\t" + "t2线程CASresult修改成功否：" + b);
            System.out.println(Thread.currentThread().getName() + "\t" + markableReference.isMarked()); // 最新值
            System.out.println(Thread.currentThread().getName() + "\t" + markableReference.getReference());

        }, "t2").start();
    }
}
